package com.woniu.rabbit.delay_model.exchange;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * 声明延迟交换机
 * */
@Slf4j
@Configuration
public class DelayExchangeConfig {
    public static final String DELAYX_QUEUE = "mq_delayx__queue";
    public static final String DELAYX_ROUTING_KEY = "mq_delayx_routing_key";
    public static final String DELAYX_EXCHANGE = "mq_delayx__exchange";
    public static final String DELAYX_EXCHANGE_TYPE = "x-delayed-message";

    /**
     * 创建 延迟交换机 CustomExchange
     * */
    @Bean
    public CustomExchange delayRoutingExchange() {
        // 延迟交换机的内部路由类型 必须设置为 'direct'，这取决于消息的投递规则
        HashMap<String, Object> map = new HashMap<>();
        map.put("x-delayed-type", "direct");
        return new CustomExchange(
                DELAYX_EXCHANGE,        // 交换机名称
                DELAYX_EXCHANGE_TYPE,  // 交换机类型
                true,                 // 是否持久化
                false,                // 是否自动删除
                map         // 额外参数 延迟交换机的内部路由类型
        );
    }

    /**
     * 创建 延迟队列
     * */
    @Bean
    public Queue delayQueue() {
        return new Queue(DELAYX_QUEUE, true);
    }

    /**
     * 绑定队列到交换机
     * */
    @Bean
    public Binding delayBinding(Queue delayQueue, CustomExchange delayRoutingExchange) {
        return BindingBuilder.bind(delayQueue)
                .to(delayRoutingExchange)
                .with(DELAYX_ROUTING_KEY)
                .noargs();
    }
}
